<template>
  <!-- 隐患处理 待审核-->
  <view class="container">
    <hidden-danger-info :detail="detail" />
    <view class="hidden-title">整改信息</view>
    <uni-forms ref="form" :model-value="reviewInfo" :rules="rules" labelWidth="70vw" labelPosition="top">
      <cu-cell-group>
        <uni-forms-item name="planDealDeptId">
          <cu-cell
            title="整改部门"
            required
            link
            placeholder="选择部门"
            :description="reviewInfo.planChargeDeptName"
            @click="handleDeptClick()"
          />
        </uni-forms-item>
        <uni-forms-item name="planChargePersonId">
          <cu-cell
            title="整改人员"
            required
            link
            placeholder="选择人员"
            :description="reviewInfo.planChargePersonName"
            @click="handlePersonClick()"
          />
        </uni-forms-item>
        <uni-forms-item name="planDealTime">
          <uni-datetime-picker hide-second :start="now" type="datetime" @change="onTimeChange($event, 'planDealTime')">
            <cu-cell title="整改时间节点" required link placeholder="选择时间" :description="reviewInfo.planDealTime">
            </cu-cell>
          </uni-datetime-picker>
        </uni-forms-item>
        <uni-forms-item name="planAcceptanceDeptId">
          <cu-cell
            title="验收部门"
            required
            link
            placeholder="选择部门"
            :description="reviewInfo.planAcceptanceDeptName"
            @click="handleAcceptanceDeptClick()"
          />
        </uni-forms-item>
        <uni-forms-item name="planAcceptancePersonId">
          <cu-cell
            title="验收人员"
            required
            link
            placeholder="选择人员"
            :description="reviewInfo.planAcceptancePersonName"
            @click="handleAcceptancePersonClick()"
          />
        </uni-forms-item>
        <uni-forms-item name="dealMoney">
          <cu-cell title="整改资金(元)">
            <input
              type="number"
              v-model="reviewInfo.dealMoney"
              class="uni-input text-right"
              placeholder-class="placeholder__style"
              placeholder="请输入整改资金"
              maxlength="13"
            />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item name="planAcceptanceTime">
          <uni-datetime-picker
            hide-second
            :start="reviewInfo.planDealTime || now"
            type="datetime"
            :disabled="!reviewInfo.planDealTime"
            @change="onTimeChange($event, 'planAcceptanceTime')"
          >
            <cu-cell
              title="验收时间节点"
              required
              link
              placeholder="选择时间"
              :description="reviewInfo.planAcceptanceTime"
            >
            </cu-cell>
          </uni-datetime-picker>
        </uni-forms-item>
      </cu-cell-group>
      <view class="background-white bor-top">
        <uni-forms-item name="dealRequire" label="整改要求">
          <textarea
            v-model="reviewInfo.dealRequire"
            class="text-area"
            placeholder-class="placeholder__style"
            placeholder="请根据实际情况简要说明整改要求(限200字)"
            maxlength="200"
          />
        </uni-forms-item>
      </view>
      <view class="background-white bor-top bottom">
        <uni-forms-item name="emergencyPlan" label="监控措施">
          <textarea
            v-model="reviewInfo.emergencyPlan"
            class="text-area"
            placeholder-class="placeholder__style"
            placeholder="请根据实际情况简要说明监控措施要求(限200字)"
            maxlength="200"
          />
        </uni-forms-item>
      </view>
    </uni-forms>
    <view class="hidden-title" v-if="detail.approvalCommentList && detail.approvalCommentList.length > 0"
      >审批意见
    </view>
    <view
      class="background-white bor-top bottom"
      v-if="detail.approvalCommentList && detail.approvalCommentList.length > 0"
    >
      <approve-suggestion :suggestion="detail.approvalCommentList"></approve-suggestion>
    </view>
    <view class="submit-group">
      <button @click="submit" class="u-button block" :ripple="true">审核</button>
      <button @click="handleEnd" class="u-button u-button-danger block" :ripple="true">结束</button>
      <button @click="handleTransfer" class="u-button block u-button-default" :ripple="true">转办</button>
    </view>

    <dept-selector ref="deptSelectorRef" @change="onDeptSelectorChange" />
    <dept-selector ref="acceptanceDeptSelectorRef" @change="onAcceptanceDeptSelectorChange" />
    <user-selector ref="userSelectorRef" :dept-id="reviewInfo.planDealDeptId" @change="onUserSelectorChange" />
    <user-selector
      ref="acceptanceUserSelectorRef"
      :dept-id="reviewInfo.planAcceptanceDeptId"
      @change="onAcceptanceUserSelectorChange"
    />
  </view>
</template>

<script>
import { getHiddenDangerDetail } from '@/api/dbd/hiddenDangerBook'
import { hiddenDangerCheckReview } from '@/api/dbd/hiddenDangerDeal'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import HiddenDangerInfo from './components/HiddenDangerInfo'
import UserSelector from '@/components/user-selector/index.vue'
import DeptSelector from '@/components/dept-selector/index.vue'
import ApproveSuggestion from './components/approveSuggestion'
import dayjs from 'dayjs'
export default {
  components: {
    HiddenDangerInfo,
    CuCellGroup,
    CuCell,
    DeptSelector,
    UserSelector,
    ApproveSuggestion
  },
  data() {
    return {
      managerId: '',
      detail: {},
      now: Date.now(),
      area: '',
      reviewInfo: {
        planDealDeptId: '',
        planChargeDeptName: '',
        planChargePersonId: '',
        planChargePersonName: '',
        dealMoney: '',
        planStartTime: Date.now(),
        planDealTime: '',
        dealRequire: '',
        emergencyPlan: '',
        planAcceptanceTime: '',
        planAcceptancePersonId: '',
        planAcceptancePersonName: '',
        planAcceptanceDeptId: '',
        planAcceptanceDeptName: ''
      },
      excludeIds: [],
      rules: {
        planDealDeptId: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        planChargePersonId: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        dealMoney: {
          rules: [
            {
              pattern: /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/,
              errorMessage: '整改资金金额不小于0（最多精确到分）'
            }
          ]
        },
        planDealTime: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            },
            {
              validateFunction: (rule, value, data, callback) => {
                let nowDate = dayjs(this.now).add(1, 'day').format('YYYY-MM-DD HH:mm')
                if (value && value < nowDate) {
                  return callback('整改时间节点需大于当前时间1天以上')
                }
                return true
              }
            }
          ]
        },
        planAcceptanceTime: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            },
            {
              validateFunction: (rule, value, data, callback) => {
                let nextDay = dayjs(this.reviewInfo.planDealTime).add(2, 'day').format('YYYY-MM-DD HH:mm')
                if (value && value < nextDay) {
                  return callback('验收时间节点需大于整改时间节点2天以上')
                }
                return true
              }
            }
          ]
        },
        planAcceptanceDeptId: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        planAcceptancePersonName: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        }
      }
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  onLoad({ managerId }) {
    this.managerId = managerId
    this.getDetail(managerId)
  },
  methods: {
    getDetail(managerId) {
      getHiddenDangerDetail(managerId).then((res) => {
        this.detail = res.data
      })
    },
    // 转办
    handleTransfer() {
      uni.navigateTo({
        url: '/pages/work/hiddenDangerDeal/transfer?managerId=' + this.managerId
      })
    },
    // 结束
    handleEnd() {
      uni.navigateTo({
        url: '/pages/work/hiddenDangerDeal/end?managerId=' + this.managerId
      })
    },
    // 保存事件
    submit() {
      const eventChannel = this.getOpenerEventChannel()
      this.$refs.form.validate().then((res) => {
        hiddenDangerCheckReview({
          ...this.reviewInfo,
          managerId: this.detail.managerId
        }).then(() => {
          this.$modal.msgSuccess('保存成功')
          eventChannel.emit('reloadEvent', true)
          uni.navigateBack({
            delta: 1
          })
        })
      })
    },
    /**
     * 部门点击事件
     */
    handleDeptClick() {
      this.$refs.deptSelectorRef.open()
    },
    /**
     * 部门点击事件
     */
    handlePersonClick() {
      if (this.reviewInfo.planDealDeptId === '') {
        this.$modal.msgError('请先选择部门')
        return
      }
      if (this.reviewInfo.planAcceptancePersonId) {
        this.excludeIds = [this.reviewInfo.planAcceptancePersonId]
      }
      this.$refs.userSelectorRef.open()
    },
    /**
     * 部门选择事件
     */
    onDeptSelectorChange({ name, value }) {
      this.reviewInfo.planDealDeptId = value
      this.reviewInfo.planChargeDeptName = name
      this.reviewInfo.planChargePersonId = ''
      this.reviewInfo.planChargePersonName = ''
    },
    /**
     * 部门选择事件
     */
    onAcceptanceDeptSelectorChange({ name, value }) {
      this.reviewInfo.planAcceptanceDeptId = value
      this.reviewInfo.planAcceptanceDeptName = name
      this.reviewInfo.planAcceptancePersonId = ''
      this.reviewInfo.planAcceptancePersonName = ''
    },
    /**
     * 验收人员点击事件
     */
    handleAcceptancePersonClick() {
      if (this.reviewInfo.planAcceptanceDeptId === '') {
        this.$modal.msgError('请先选择部门')
        return
      }
      if (this.reviewInfo.planChargePersonId) {
        this.excludeIds = [this.reviewInfo.planChargePersonId]
      }
      this.$refs.acceptanceUserSelectorRef.open()
    },
    /**
     * 人员选择事件
     */
    onAcceptanceUserSelectorChange({ name, value }) {
      this.reviewInfo.planAcceptancePersonId = value
      this.reviewInfo.planAcceptancePersonName = name
    },
    /**
     * 验收部门点击事件
     */
    handleAcceptanceDeptClick() {
      this.$refs.acceptanceDeptSelectorRef.open()
    },
    /**
     * 人员选择事件
     */
    onUserSelectorChange({ name, value }) {
      this.reviewInfo.planChargePersonId = value
      this.reviewInfo.planChargePersonName = name
    },
    /**
     * 时间选择
     */
    onTimeChange(val, key) {
      console.log('onTimeChange val', val)
      this.reviewInfo[key] = dayjs(val.trim()).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 200rpx;

  .background-white {
    background-color: #fff;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .uni-forms-item__label {
      color: #333;
      font-size: 30rpx;
    }

    .bor-btm {
      display: flex;
      border-bottom: 1px solid #d5d7e3;
    }

    .photo {
      display: flex;
      justify-content: space-between;

      image {
        width: 214rpx;
        height: 214rpx;
      }
    }
  }
}

.approve-text {
  font-size: 30rpx;
  font-weight: 400;
  background: #ffffff;

  .approve {
    padding: 20rpx;
  }
}

.hidden-title {
  background: #f5f5f5;
  padding: 20rpx;
  color: #999;
}

.bor-top {
  border-top: 20rpx solid #f5f5f5;
}
</style>
